package com.djf.djfword.service;

import org.apache.poi.xwpf.usermodel.*;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * Word文档操作服务类
 * 
 * @author djf
 */
@Service
public class WordService {

    /**
     * 创建简单的Word文档
     */
    public void createSimpleWord(HttpServletResponse response, String title, String content) throws IOException {
        // 创建空白文档
        XWPFDocument document = new XWPFDocument();
        
        // 创建标题段落
        XWPFParagraph titleParagraph = document.createParagraph();
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun titleRun = titleParagraph.createRun();
        titleRun.setText(title);
        titleRun.setBold(true);
        titleRun.setFontSize(18);
        titleRun.setFontFamily("宋体");
        
        // 创建内容段落
        XWPFParagraph contentParagraph = document.createParagraph();
        contentParagraph.setAlignment(ParagraphAlignment.LEFT);
        XWPFRun contentRun = contentParagraph.createRun();
        contentRun.setText(content);
        contentRun.setFontSize(12);
        contentRun.setFontFamily("宋体");
        
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename=simple_document.docx");
        
        // 写入响应流
        document.write(response.getOutputStream());
        document.close();
    }
    
    /**
     * 创建包含表格的Word文档
     */
    public void createWordWithTable(HttpServletResponse response, List<Map<String, String>> tableData) throws IOException {
        XWPFDocument document = new XWPFDocument();
        
        // 创建标题
        XWPFParagraph titleParagraph = document.createParagraph();
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun titleRun = titleParagraph.createRun();
        titleRun.setText("数据报表");
        titleRun.setBold(true);
        titleRun.setFontSize(16);
        titleRun.setFontFamily("宋体");
        
        // 添加空行
        document.createParagraph();
        
        // 创建表格
        if (tableData != null && !tableData.isEmpty()) {
            XWPFTable table = document.createTable();
            
            // 创建表头
            XWPFTableRow headerRow = table.getRow(0);
            headerRow.getCell(0).setText("序号");
            headerRow.addNewTableCell().setText("姓名");
            headerRow.addNewTableCell().setText("年龄");
            headerRow.addNewTableCell().setText("职位");
            
            // 设置表头样式
            for (XWPFTableCell cell : headerRow.getTableCells()) {
                cell.setColor("E6E6FA");
                XWPFParagraph p = cell.getParagraphs().get(0);
                p.setAlignment(ParagraphAlignment.CENTER);
                XWPFRun run = p.getRuns().get(0);
                run.setBold(true);
                run.setFontFamily("宋体");
            }
            
            // 添加数据行
            for (int i = 0; i < tableData.size(); i++) {
                Map<String, String> rowData = tableData.get(i);
                XWPFTableRow dataRow = table.createRow();
                dataRow.getCell(0).setText(String.valueOf(i + 1));
                dataRow.getCell(1).setText(rowData.getOrDefault("name", ""));
                dataRow.getCell(2).setText(rowData.getOrDefault("age", ""));
                dataRow.getCell(3).setText(rowData.getOrDefault("position", ""));
                
                // 设置数据行样式
                for (XWPFTableCell cell : dataRow.getTableCells()) {
                    XWPFParagraph p = cell.getParagraphs().get(0);
                    p.setAlignment(ParagraphAlignment.CENTER);
                    XWPFRun run = p.getRuns().get(0);
                    run.setFontFamily("宋体");
                }
            }
        }
        
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename=table_document.docx");
        
        // 写入响应流
        document.write(response.getOutputStream());
        document.close();
    }
    
    /**
     * 读取Word文档内容
     */
    public String readWordContent(InputStream inputStream) throws IOException {
        XWPFDocument document = new XWPFDocument(inputStream);
        StringBuilder content = new StringBuilder();
        
        // 读取段落内容
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs) {
            content.append(paragraph.getText()).append("\n");
        }
        
        // 读取表格内容
        List<XWPFTable> tables = document.getTables();
        for (XWPFTable table : tables) {
            content.append("\n=== 表格内容 ===\n");
            for (XWPFTableRow row : table.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    content.append(cell.getText()).append("\t");
                }
                content.append("\n");
            }
        }
        
        document.close();
        return content.toString();
    }
    
    /**
     * 创建模板Word文档（包含多种元素）
     */
    public void createTemplateWord(HttpServletResponse response, Map<String, String> data) throws IOException {
        XWPFDocument document = new XWPFDocument();
        
        // 1. 创建文档标题
        XWPFParagraph titleParagraph = document.createParagraph();
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun titleRun = titleParagraph.createRun();
        titleRun.setText(data.getOrDefault("title", "文档标题"));
        titleRun.setBold(true);
        titleRun.setFontSize(20);
        titleRun.setFontFamily("宋体");
        
        // 2. 添加日期
        XWPFParagraph dateParagraph = document.createParagraph();
        dateParagraph.setAlignment(ParagraphAlignment.RIGHT);
        XWPFRun dateRun = dateParagraph.createRun();
        dateRun.setText("日期：" + data.getOrDefault("date", "2024-01-01"));
        dateRun.setFontSize(12);
        dateRun.setFontFamily("宋体");
        
        // 3. 添加空行
        document.createParagraph();
        
        // 4. 添加正文内容
        XWPFParagraph contentParagraph = document.createParagraph();
        contentParagraph.setAlignment(ParagraphAlignment.BOTH);
        XWPFRun contentRun = contentParagraph.createRun();
        contentRun.setText(data.getOrDefault("content", "这里是文档的正文内容..."));
        contentRun.setFontSize(12);
        contentRun.setFontFamily("宋体");
        
        // 5. 添加列表
        XWPFParagraph listTitle = document.createParagraph();
        XWPFRun listTitleRun = listTitle.createRun();
        listTitleRun.setText("\n要点列表：");
        listTitleRun.setBold(true);
        listTitleRun.setFontSize(14);
        listTitleRun.setFontFamily("宋体");
        
        String[] listItems = {"第一个要点", "第二个要点", "第三个要点"};
        for (int i = 0; i < listItems.length; i++) {
            XWPFParagraph listItem = document.createParagraph();
            XWPFRun listRun = listItem.createRun();
            listRun.setText((i + 1) + ". " + listItems[i]);
            listRun.setFontSize(12);
            listRun.setFontFamily("宋体");
        }
        
        // 6. 添加签名
        XWPFParagraph signatureParagraph = document.createParagraph();
        signatureParagraph.setAlignment(ParagraphAlignment.RIGHT);
        XWPFRun signatureRun = signatureParagraph.createRun();
        signatureRun.setText("\n\n签名：" + data.getOrDefault("signature", "_____________"));
        signatureRun.setFontSize(12);
        signatureRun.setFontFamily("宋体");
        
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename=template_document.docx");
        
        // 写入响应流
        document.write(response.getOutputStream());
        document.close();
    }
}